package com.kgc.est.utils.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SendSmsUtils {
    @Autowired
    private AliSmsConfig aliSmsConfig;

    /**
     *发送短信的方法
     * @param phone  接收短信的手机号
     * @param code   接收的核心内容-- 验证码
     * @return
     */
    public boolean sendSms(String phone,String code){

        DefaultProfile profile = DefaultProfile.getProfile(aliSmsConfig.getRefionId(),
                aliSmsConfig.getAccessKey(),
                aliSmsConfig.getAccessKeySecret());
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST); // 发送短信的请求方式post
        request.setDomain(aliSmsConfig.getDomain()); // 阿里短信的服务域名
        request.setVersion(aliSmsConfig.getVersion()); //
        request.setAction(aliSmsConfig.getAction());
        //request.putQueryParameter("RegionId", "default");//固定参数，填写default默认值即可，同第一行参数
        request.putQueryParameter("PhoneNumbers", phone);//需要接收验证码的手机号
        request.putQueryParameter("SignName", aliSmsConfig.getSignName());//短信签名名称，必须与申请通过的签名保持一致
        request.putQueryParameter("TemplateCode", aliSmsConfig.getTemplateCode());//短信模板ID，必须与申请通过的模板ID保持一致
        Map<String, String> map = new HashMap<String, String>();
        map.put("code", code);
        request.putQueryParameter("TemplateParam",
                com.alibaba.fastjson.JSON.toJSONString(map));//短信模板变量对应的实际值，JSON格式，例如：{"code":"1111"}
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
